<template>
  <div>
    <el-form ref="form" v-if="tempData.isEndNode === '1'">
      <el-row>
        <el-col :span="8">
          <el-form-item label="员工工号" label-width="80px">
            <el-input v-model="searchParams.userId" placeholder="请输入员工工号"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="用户姓名" label-width="80px">
            <el-input v-model="searchParams.employeeName" placeholder="请输入用户姓名"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" style="padding-left: 10px;padding-top: 5px;">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="reset">重置</el-button>
        </el-col>
        <el-col :span="24">
          <el-table ref="userTable" :row-key="getRowKey" :data="employeeList" @selection-change="handleSelectedUser"
                    highlight-current-row>
            <el-table-column type="selection" :reserve-selection="true" width="55" align="enter"/>
            <el-table-column label="序号" align="center" type="index"/>
            <el-table-column label="员工工号" align="center" prop="userId" :show-overflow-tooltip="true"/>
            <el-table-column label="用户姓名" align="center" prop="employeeName" :show-overflow-tooltip="true"/>
            <el-table-column label="部门名称" align="center" prop="orgName" :show-overflow-tooltip="true"/>
          </el-table>
          <!-- 分页 -->
          <pagination
                  v-show="total>0"
                  :total="total"
                  :page.sync="pageParams.page"
                  :limit.sync="pageParams.rows"
                  :pageSizes.sync="pageParams.pageSizes"
                  :pager-count="5"
                  @pagination="getList"
          />
        </el-col>
      </el-row>
    </el-form>
    <div>
      <el-form>
        <el-row>
          <el-col :span="24" v-if="tempData.isEndNode === '1'">
            <el-form-item label="下一步审批人" label-width="100px">
              <el-tag v-for="user in selectedUserList" :key="user.userId" closable @close="handleTagClose(user)">
                {{ user.employeeName }}
              </el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审批意见" label-width="100px">
              <el-input type="textarea" maxlength="300" v-model="remark" placeholder="请输入审批意见"
                        :autosize="{ minRows: 4 }"
                        show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div>
      <el-button type="primary" size="small" v-loading="loading" @click="handlProcess">提 交</el-button>
      <el-button v-if="processStatus === '1'" type="primary" size="small" @click="handleBack">选择退回节点</el-button>
      <el-button size="small" @click="closeVerify">取 消</el-button>
    </div>
    <el-dialog title="选择回退节点" v-if="open" :visible.sync="open" width="400px" append-to-body>
      <BackPage :backNodeList="backNodeList" :process-params="tempData" :historyList="historyList"
                :isRouting="isRouting" @submitBackPage="closeVerify" @closeBackPage="closeBackPage"></BackPage>
    </el-dialog>
  </div>
</template>
<script>
  import {startWorkFlow, nextNode, getNodeUserList, nextNodeAndUserList, getAllNodeInfo} from '@/api/workflow/workFlow'
  import BackPage from "@/views/workflow/components/form/BackPage";
  export default {
    props: {
      // 流程状态（0：发起流程，1：流程流转）
      processStatus: String,
      // 流程历史记录
      historyList: Array
    },
    components: {
      BackPage
    },
    data() {
      return {
        // 复选框是否支持多选
        multiple: true,
        // 遮罩层
        loading: false,
        // 查询用户信息
        searchParams: {},
        // 意见
        remark: '',
        // 总用户信息列表
        employeeListTotal: [],
        // 显示用户信息列表
        employeeList: [],
        // 已选用户列表
        selectedUserList: [],
        // 总条数
        total: 0,
        // 分页参数
        pageParams: {
          page: 1,
          rows: 8,
          pageSizes: [8, 16, 24, 32, 40]
        },

        // 暂存流程需要的数据
        tempData: {},
        // 回退页面开关
        open: false,
        // 退回节点列表
        backNodeList: [],
        // 节点是否有路由条件
        isRouting: false
      }
    },
    methods: {
      // 初始化
      init(processParams) {
        // 初始化时查询节点、用户信息
        const responseNodes = {};
        responseNodes.formData = processParams.formData;
        responseNodes.taskId = processParams.taskId;
        if (this.processStatus === '0') { // 流程状态（0：发起流程，1：流程流转）
          getNodeUserList(processParams).then(response => {
            if(response.retCode === '200'){
              responseNodes.processId = processParams.processId;
              responseNodes.processName = processParams.processName
              responseNodes.businessId = processParams.businessId // 业务id
              responseNodes.link = processParams.link  // 待办表单路径
              responseNodes.isEndNode = '1' // 是否是结束节点：0：结束节点：1：非结束节点
              responseNodes.rows = response.responseBody.rows
              responseNodes.nextNodeId = response.responseBody.nextNodeId;
              responseNodes.nextNodeName = response.responseBody.nextNodeName;
              responseNodes.url = processParams.url // 流程实例对应的业务服务url
              this.setResponseNodes(responseNodes)
            }else {
              this.$message.error(response.message)
            }
          })
        } else if(this.processStatus === '1'){
          nextNodeAndUserList(processParams).then(response => {
            if(response.retCode === '200'){
              if(response.responseBody.isEndNode === '1'){ // 是否是结束节点：0：结束节点：1：非结束节点
                responseNodes.rows = response.responseBody.rows
              }
              responseNodes.nextNodeList = response.responseBody.nextNodeList
              responseNodes.nextNodeName = response.nextNodeName
              responseNodes.isEndNode = response.responseBody.isEndNode
              responseNodes.nextNodeId = response.responseBody.nextNodeId;
              responseNodes.nextNodeName = response.responseBody.nextNodeName;
              responseNodes.docUnid = processParams.docUnid;
              responseNodes.currentNodeId = processParams.currentNodeId;
              responseNodes.currentNodeName = processParams.currentNodeName
              responseNodes.startTime = processParams.startTime
              responseNodes.link = processParams.link
              responseNodes.processId = processParams.processId
              responseNodes.processName = processParams.processName
              responseNodes.businessId = processParams.businessId
              this.setResponseNodes(responseNodes);
            }else {
              this.$message.error(response.message)
            }
          })
        }
      },

      setResponseNodes(responseNodes) {
        if (responseNodes.isEndNode === '1') {
          // 非结束节点需要初始化选人信息
          this.employeeList = this.employeeListTotal = responseNodes.rows;
          this.total = this.employeeListTotal.length
          this.tempData.isEndNode = '1'
        }
        this.tempData = responseNodes
        this.getList()
      },

      // 获取用户信息
      getList() {
        let temp = new Array();
        // 如果有查询条件，则条件查询
        if (Object.keys(this.searchParams).length > 0) {
          // 递归条件查询
          temp = this.conditionQuery(this.employeeListTotal, this.searchParams, Object.keys(this.searchParams).length)
        } else {
          temp = this.employeeListTotal
        }
        // 分页
        this.employeeList = temp.slice((this.pageParams.page - 1) * this.pageParams.rows, this.pageParams.page * this.pageParams.rows)
        this.total = temp.length
      },

      /**
       * 条件查询
       * list：待查询列表
       * searchParams：查询参数（0个或多个）
       * len：查询参数个数
       */
      conditionQuery (list, searchParams, len) {
        if (len === 0) {
          return list
        }
        // 获取最后一个查询参数的key
        let key = Object.keys(searchParams)[len - 1]
        let temp = []
        list.forEach(item => {
          // 将匹配成功的记录保存并用于下一次递归匹配
          if (item[key].indexOf(searchParams[key]) > -1) {
            temp.push(item)
          }
        })
        return this.conditionQuery(temp, searchParams, len - 1)
      },

      // 重置
      reset() {
        this.searchParams = {}
        this.getList()
      },
      // 多选框选中数据处理
      handleSelectedUser(item) {
        if (this.multiple) {// 支持多选
          this.selectedUserList = item
        } else {// 支持单选
          this.selectedUserList = item
          if (item.length > 1) {
            let delRow = item.shift();
            this.$refs.userTable.toggleRowSelection(delRow, false)
          }
          if (item.length === 0) {
            this.selectedUserList = null
          }
        }
      },
      // 删除tag
      handleTagClose(user) {
        this.selectedUserList.splice(this.selectedUserList.indexOf(user), 1)
        this.$refs.userTable.toggleRowSelection(user, false)
      },

      // 处理流程
      handlProcess() {
        // 如果不是最后一个节点（isEndNode：0：最后节点，1：非最后节点），则检查是否选择了审批人
        if(this.tempData.isEndNode === '1' && this.selectedUserList.length === 0) {
          this.msgError("未设置“下一步审批人”")
          return
        }
        var nextUserId = ''
        var nextUserName = ''
        if(this.tempData.isEndNode === '1') {
          // 选人格式化
          this.selectedUserList.forEach(x => {
            nextUserId = nextUserId + x.userId + ','
            nextUserName += x.employeeName + ','
          })
          nextUserId = nextUserId.substr(0, nextUserId.length - 1)
          nextUserName = nextUserName.substr(0, nextUserName.length - 1)
        }
        // processStatus：0：启动流程，1：流程流转
        if (this.processStatus === '0') {
          this.startProcess(nextUserId, nextUserName)
        } else if (this.processStatus === '1') {
          this.processFlow(nextUserId, nextUserName)
        }
      },

      // 启动流程
      startProcess(nextUserId, nextUserName) {
        // 启动流程需要的数据
        let submitData = {}
        submitData.userName = this.$store.getters.name// 创建人
        submitData.businessId = this.tempData.businessId // 业务id
        submitData.processId = this.tempData.processId // 流程模型id
        submitData.processName = this.tempData.processName // 流程名
        submitData.nextNodeId = this.tempData.nextNodeId // 下一个节点id
        submitData.nextNodeName = this.tempData.nextNodeName // 下一个节点名
        submitData.nextUserId = nextUserId // 下一个节点处理人id
        submitData.nextUserName = nextUserName
        submitData.link = this.tempData.link // 页面表单路径
        submitData.subject = this.tempData.subject // 业务名
        submitData.remark = this.remark // 意见
        submitData.url = this.tempData.url // 流程实例对应的业务服务url
        this.loading = true
        startWorkFlow(submitData).then(response => {
          if (response.retCode !== '200') {
            this.msgError(response.message)
            return
          }
          this.msgSuccess(response.message);
          this.$emit('closeVerify')
        }).finally(() => {
          this.loading = false
        })
      },

      // 流程流转
      processFlow(nextUserId, nextUserName) {
        // 流程流转需要的数据
        let submitData = {}
        submitData.taskId = this.tempData.taskId // 待办id
        submitData.processId = this.tempData.processId
        submitData.processName = this.tempData.processName
        submitData.docUnid = this.tempData.docUnid // 流程实例id
        submitData.currentNodeId = this.tempData.currentNodeId // 当前节点id
        submitData.currentNodeName = this.tempData.currentNodeName // 当前节点名
        submitData.nextNodeList = this.tempData.nextNodeList // 下一个节点
        submitData.nextNodeName = this.tempData.nextNodeName // 下一个节点名
        submitData.nextUserList = this.tempData.isEndNode === '1' ? nextUserId : '' // 下一个处理用户列表，最后一个节点不设置用户
        submitData.nextUserName = this.tempData.isEndNode === '1'? nextUserName : ''
        submitData.remark = this.remark // 意见
        submitData.startTime = this.tempData.startTime
        submitData.link = this.tempData.link
        submitData.businessId = this.tempData.businessId
        submitData.isEndNode = this.tempData.isEndNode // 是否结束节点
        submitData.formData = this.tempData.formData; // 路由条件
        this.loading = true
        nextNode(submitData).then(response => {
          if (response.retCode !== '200') {
            this.msgError(response.message)
            return
          }
          this.msgSuccess(response.message);
          this.$emit('closeVerify')
        }).finally(() => {
          this.loading = false
        })
      },

      // 退回
      handleBack () {
        // 初始化
        this.backNodeList = []
        const queryParams = {}
        queryParams.processId = this.tempData.processId
        queryParams.docUnid = this.tempData.docUnid
        queryParams.currentNodeId = this.tempData.currentNodeId
        queryParams.formData = this.tempData.formData
        getAllNodeInfo(queryParams).then(resp => {
          // 所有节点列表
          const allNodes = resp.responseBody
          // 当前节点是否是‘发起流程’节点标志
          let isStartNode = false
          for (let i = 0; i < allNodes.length; i++) {
            // 去除‘开始’、‘结束’及当前节点之后的节点
            if (allNodes[i].NodeName === '开始' || allNodes[i].NodeName === '结束' ||
                allNodes[i].Nodeid >= this.tempData.currentNodeId) {
              continue
            }
            this.backNodeList.push(allNodes[i])
          }

          // 如果当前为‘发起流程’节点，则不用退回
          if (this.backNodeList.length === 0) {
            this.$message.error("当前为”发起流程“节点，不能退回")
            return
          }

          // 判断是否是有路由条件的节点
          if (JSON.parse(this.tempData.formData).hasInspectors) {
            this.isRouting = true
          } else {
            this.isRouting = false
          }

          // 若是军民机流程但无检验，则去除检验节点(hasInspectors：0：无检验，1：有检验) FIXME 如果有路由条件的节点需要根据条件筛选节点，目前还有军民机有路由条件，此判断方法非通用
          if (JSON.parse(this.tempData.formData).hasInspectors === '0') {
            // 要删除节点的下标
            let remove
            for (let i = 0; i < this.backNodeList.length; i++) {
              // T10004检验节点
              if (this.backNodeList[i].Nodeid === 'T10004') {
                remove = i
              }
            }
            this.backNodeList.splice(remove, 1)
          }

          // 打开回退页面
          this.open = true
        })
      },

      // 关闭页面
      closeVerify() {
        this.$emit('closeVerify')
      },

      // 关闭退回页面
      closeBackPage () {
        this.open = false
      },

      getRowKey(row){
        return row.id
      }
    }
  }
</script>
